package com.zhoug.common3.permission;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import java.util.ArrayList;
import java.util.Locale;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

/**
 * 权限申请页面
 */
public class PermissionsActivity extends AppCompatActivity {
    private static final String TAG = ">>>PermissionActivity";
    private boolean debug = false;
    private ArrayList<String> mPermissions;
    private boolean mShowNoAsking;
    private boolean mShowDescription;
    private String mDescription;
    private int mRequestCode;
    private String mAction;
    private ActivityResultLauncher<Intent> mNotAskingLauncher;

//    private static final int REQUEST_SETTING = 1194;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        debug = ZPermissions.isDebug();
        init();
    }

    private void init() {
        mNotAskingLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //设置权限回掉
                if (result != null) {
                    //存储申请成功的权限
                    ArrayList<String> granted = new ArrayList<>();
                    //存储未申请成功的权限
                    ArrayList<String> denied = new ArrayList<>();
                    for (int i = 0; i < mPermissions.size(); i++) {
                        String permission = mPermissions.get(i);
                        if (ActivityCompat.checkSelfPermission(PermissionsActivity.this, permission) == PackageManager.PERMISSION_GRANTED) {
                            granted.add(permission);
                        } else {
                            denied.add(permission);
                        }
                    }
                    //全部权限是否授权
                    boolean allGranted = granted.size() == mPermissions.size();
                    if (debug) {
                        Log.d(TAG, "granted:" + granted);
                        Log.d(TAG, "denied:" + denied);
                        Log.d(TAG, "allGranted:" + allGranted);
                    }
                    sendBroadcast(allGranted, granted, denied);
                    finish();
                }
            }
        });


        Intent intent = getIntent();
        if (intent != null) {
            mPermissions = intent.getStringArrayListExtra("permissions");
            mShowNoAsking = intent.getBooleanExtra("showNoAsking", false);
            mRequestCode = intent.getIntExtra("requestCode", 1638);
            mAction = intent.getStringExtra("action");
            mShowDescription = intent.getBooleanExtra("showDescription", false);
            mDescription = intent.getStringExtra("description");
        }


        if (mShowDescription) {
            if(mDescription==null){
                mDescription=String.format(Locale.CANADA,"此功能需要%s权限才能正常使用",MUtils.getNames(mPermissions));
            }
            IPermissionDescriptionDialog permissionDescriptionDialog = ZPermissions.getPermissionDescriptionDialog();
            permissionDescriptionDialog.show(this, mDescription, new PermissionDescriptionDialog.Callback() {
                @Override
                public void onConfirm() {
                    requestPermission();
                }

                @Override
                public void onRefuse() {
                    sendBroadcast(false, null, mPermissions);
                    finish();
                }
            });
        } else {
            requestPermission();
        }

    }



    private void requestPermission() {
        //申请权限
        String[] perms = new String[mPermissions.size()];
        perms = mPermissions.toArray(perms);
        ActivityCompat.requestPermissions(this, perms, mRequestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == this.mRequestCode) {
            if (debug) {
                Log.d(TAG, "onRequestPermissionsResult:permissions=" + MUtils.toString(permissions));
            }
            //存储申请成功的权限
            ArrayList<String> granted = new ArrayList<>();
            //存储未申请成功的权限
            ArrayList<String> denied = new ArrayList<>();
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                        denied.add(permissions[i]);
                    } else {
                        granted.add(permissions[i]);
                    }
                }
            }
            //全部权限是否授权
            boolean allGranted = granted.size() == permissions.length;
            if (debug) {
                Log.d(TAG, "granted:" + granted);
                Log.d(TAG, "denied:" + denied);
                Log.d(TAG, "allGranted:" + allGranted);
            }

            ArrayList<String> noAskPermissions = new ArrayList<>();
            //请求失败,要显示提示
            if (!allGranted && mShowNoAsking) {
                for (String per : permissions) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, per)) {
                        noAskPermissions.add(per);
                    }
                }
            }
            if (debug) {
                Log.d(TAG, "onRequestPermissionsResult:noAskPermissions=" + noAskPermissions);
            }
            //全部权限都勾选了不在询问
            if (noAskPermissions.size() == permissions.length) {
                showNotAskingDialog(noAskPermissions, granted, denied);
            } else {
                //发送广播通知权限申请完成
                sendBroadcast(allGranted, granted, denied);
                finish();
            }
        }
    }

    /**
     * 用户点击了不再询问后显示的提示
     */
    private void showNotAskingDialog(final ArrayList<String> noAskingPermission, final ArrayList<String> granted, final ArrayList<String> denied) {
        Log.i(TAG, "showNotAskingDialog: ");
        INotAskingPermissionDialog notAskingPermissionDialog = ZPermissions.getNotAskingPermissionDialog();
        notAskingPermissionDialog.show(this, noAskingPermission, new INotAskingPermissionDialog.Callback() {
            @Override
            public void onConfirm() {
                try {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
//                    startActivityForResult(intent, REQUEST_SETTING);
                    mNotAskingLauncher.launch(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    sendBroadcast(false, granted, denied);
                    finish();
                }
            }

            @Override
            public void onCancel() {
                sendBroadcast(false, granted, denied);
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置权限回掉
       /* if (requestCode == REQUEST_SETTING) {
            //存储申请成功的权限
            ArrayList<String> granted = new ArrayList<>();
            //存储未申请成功的权限
            ArrayList<String> denied = new ArrayList<>();
            for (int i = 0; i < mPermissions.size(); i++) {
                String permission = mPermissions.get(i);
                if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
                    granted.add(permission);
                } else {
                    denied.add(permission);
                }
            }
            //全部权限是否授权
            boolean allGranted = granted.size() == mPermissions.size();
            if (debug) {
                Log.d(TAG, "granted:" + granted);
                Log.d(TAG, "denied:" + denied);
                Log.d(TAG, "allGranted:" + allGranted);
            }
            sendBroadcast(allGranted, granted, denied);
            finish();
        }*/
    }

    /**
     * 发送广播通知权限申请完成
     *
     * @param allGranted
     * @param granted
     * @param denied
     */
    private void sendBroadcast(boolean allGranted, ArrayList<String> granted, ArrayList<String> denied) {
        Intent broadcastIntent = new Intent(mAction);
        broadcastIntent.putExtra("success", allGranted);
        broadcastIntent.putStringArrayListExtra("granted", granted);
        broadcastIntent.putStringArrayListExtra("denied", denied);
        sendBroadcast(broadcastIntent);
    }

    @Override
    public void onBackPressed() {
        sendBroadcast(false, null, mPermissions);
        super.onBackPressed();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mNotAskingLauncher!=null){
            mNotAskingLauncher.unregister();
        }
    }

}
